package com.fingard.dsp.bank.directbank.tenpay01;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.crypto.DigestHelper;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;

public class TENPAY01Base extends DirectBase {
	private static int fileIncrement = 1;
	
	protected String getCharset(){
		return getBankConfig().getCharset("GBK");
	}
	
	/**
	 * 创建财付通请求文件
	 * 文件路径示例：D:\Dsp\Dsp\TempFile\TenPay01\Rec_Request\2013-06\20\00080M53_02281253_0005.csv
	 * 
	 * @param p_NamePrefix  批次号
	 */
	protected File createFile(String p_NamePrefix) throws IOException {
		String tmpByDate = Format.Date10Format.format(new Date());
		tmpByDate = tmpByDate.substring(0,7)+File.separator+tmpByDate.substring(8,10);
		
		int tmpFileID = fileIncrement++;
        if (tmpFileID > 9999){
        	fileIncrement = 0;
            tmpFileID = fileIncrement++;
        }
        
        String filePath = FGBiz.dspCenter.dataDirPath+File.separator + "TempFile" + File.separator + "TenPay01" + File.separator + "Rec_Request" + File.separator+tmpByDate+ File.separator;
       
        filePath += p_NamePrefix + "_" + Format.TimeSSFormat.format(new Date()).substring(0,8) + "_" + String.format("%4s", tmpFileID).replace(' ', '0') + ".csv";
        
        File sendFile = new File(filePath);
        
        if (!sendFile.getParentFile().exists()) {
        	sendFile.getParentFile().mkdirs();
        }
        
        if (!sendFile.exists()) {
        	sendFile.createNewFile();
        }
        
        return sendFile;
	}
	
	/**
	 * 生成并返回file_body
	 */
	protected String getFileBody(ReqBatPayRec p_req9188) throws Exception {
		StringBuilder sbSend = new StringBuilder();
		
		String service_code = getBankConfig().getMapAdvanceValue("businessCode_"+p_req9188.reqHeader.transType, "srcCode", "desCode", p_req9188.useType);
		
		String tmpUsage = p_req9188.useType;
		if (StringHelper.isNullOrEmpty(tmpUsage)) {
			tmpUsage = "代扣";
		}
		
		sbSend.append("批次号,总笔数,总金额(元),业务代码,扣款说明\r\n");
		sbSend.append(p_req9188.reqBatchNO +","+p_req9188.totalNum+","+StringHelper.amountMultiply100(p_req9188.totalAmt)+","+service_code+","+tmpUsage+"\r\n");
		sbSend.append("单笔序列号,单笔代扣单号(可选),代扣金额(元),开户银行,账户类型,卡类型,银行账号,开户人姓名,证件类型(可选),证件号(可选),信用卡有效期(可选),信用卡CVV(可选),手机号(可选),扣款说明\r\n");
		
		int tmpSerialNumber = 1;
		while (p_req9188.readRecord()) {
			String payAmount = StringHelper.amountMultiply100(p_req9188.readedDetail.payAmount);
			// 银行字母编码
			String bankCode = getBankConfig().getMapKeyByValue("BankCodeMapping", p_req9188.readedDetail.payBankName);
			
			// 账户类型
			String bankType = "";
			if (p_req9188.readedDetail.isPrivate.equals("0")) {
				bankType = "公司";
			}else {
				bankType = "个人";
			}
			
			//卡类型
			String cardType = "";
			if (p_req9188.readedDetail.cardType.equals("0")) {
				cardType = "银行卡";
			}else if (p_req9188.readedDetail.cardType.equals("1")) {
				cardType = "存折";
			}else {
				cardType = "信用卡";
			}
			
			String tmpDesc = p_req9188.readedDetail.memo;
			if (StringHelper.isNullOrEmpty(tmpDesc)) {
				tmpDesc = p_req9188.readedDetail.useType;
			}
			if (StringHelper.isNullOrEmpty(tmpDesc)) {
				tmpDesc = "代扣";
			}
			
			sbSend.append(tmpSerialNumber+","+p_req9188.readedDetail.askNumber+","+payAmount+","+bankCode+","+bankType+","+cardType+","+p_req9188.readedDetail.payAct+","+p_req9188.readedDetail.payName+","+""+","+""+","+""+","+""+","+""+","+tmpDesc+"\r\n");
			
			tmpSerialNumber++;
		}
		
		return sbSend.toString();
	}
	
	/**
	 * 签名原始串并生成sign
	 * 
	 * retStr[0]:发送财付通请求数据
	 * retStr[1]:sign
	 */
	protected String[] signMessage(HashMap<String,String> p_mapParams, String p_saltKey) throws Exception{
		String[] retStr = new String[]{"","",""};
		TreeMap<String, String> treeMap = new TreeMap<String, String>();
		
		for(Map.Entry<String, String> entry:p_mapParams.entrySet()){
			String name=entry.getKey();
			String value=entry.getValue();
			if(StringHelper.hasAnyChar(value)){
				treeMap.put(name, value);
			}
		}
		
		StringBuilder retReqStr = new StringBuilder();
		for (String key : treeMap.keySet()) {
			retReqStr.append(key + ":" + treeMap.get(key) + "\r\n");
		}
		
		retStr[0] = retReqStr.toString();
		
		StringBuilder sbValues = new StringBuilder();
		for (String key : treeMap.keySet()) {
			if(sbValues.length()>0){
				sbValues.append("&");
			}
			sbValues.append(key + "=" + treeMap.get(key));
		}
        sbValues.append("&key="+p_saltKey);
        
        retStr[1] = sbValues.toString();
        
        byte[] tmpDataBytes = sbValues.toString().getBytes(getCharset());
        
        retStr[2] = DigestHelper.cryptoMD5RetHexStr(tmpDataBytes).toUpperCase();
        
		return retStr;
	}
	
	/**
	 * 发财付通
	 * @param file
	 * @param charsetName
	 * @return
	 * @throws  
	 */
	protected String[] sendToBank(File file, String reqStr, String charsetName) throws Exception{
		String[] retStr = new String[]{"",""};
		WriteBankLogLn("提交财付通地址：" + bankFront.getUrl("9188"));
		WriteBankLogLn("提交财付通内容：\r\n" + reqStr);
		WriteBankLogLn2(file.getAbsolutePath());
		
		WebRequest tmpWebRequest = new WebRequest(bankFront.getUrl("9188"));
		tmpWebRequest.setConnectTimeout(60000);
		tmpWebRequest.setRequestProperty("connection", "Close");
		
		WriteBankLogStep3(retStr[1]);
		
		return retStr;
	}
	
	protected String[] sendToBank(String reqStr, String charsetName) throws Exception{
		String[] retStr = new String[]{"",""};
		WriteBankLogLn("提交财付通地址：" + bankFront.getUrl("9198"));
		
		WebRequest tmpWebRequest = new WebRequest(bankFront.getUrl("9198"));
		tmpWebRequest.setConnectTimeout(60000);
		tmpWebRequest.setRequestProperty("connection", "Close");
		
		retStr = tmpWebRequest.upload(reqStr.getBytes(getCharset()), charsetName);
		WriteBankLogStep3(retStr[1]);
		
		return retStr;
	}
}
